package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.mapper.TeachesMapper;
import com.example.homeworkmanagement.pojo.Classes;
import com.example.homeworkmanagement.pojo.Courses;
import com.example.homeworkmanagement.mapper.CoursesMapper;
import com.example.homeworkmanagement.pojo.Teaches;
import com.example.homeworkmanagement.service.CoursesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> implements CoursesService {
    @Autowired
    private CoursesMapper coursesMapper;
    @Autowired
    private TeachesMapper teachesMapper;
    @Override
    public ResultVO<List<Courses>> getCourseList(Courses courses, int page, int size) {
        QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();

        // 使用驼峰式的getter方法获取属性值，同时指定数据库中的下划线字段名
        if (courses.getCourseId() != null && !courses.getCourseId().isEmpty()) {
            queryWrapper.like("course_id", courses.getCourseId());
        }
        if (courses.getCourseName() != null && !courses.getCourseName().isEmpty()) {
            queryWrapper.like("course_name", courses.getCourseName());
        }
        if (courses.getDepartment() != null && !courses.getDepartment().isEmpty()) {
            queryWrapper.like("department", courses.getDepartment());
        }
        if (courses.getCourseCredits() != null) {
            queryWrapper.eq("course_credits", courses.getCourseCredits());
        }
        Page<Courses> pageResult = this.page(new Page<>(page, size), queryWrapper);
        List<Courses> coursesList = this.list(queryWrapper);
        int total = coursesList.size();
        return ResultVO.success("课程列表获取成功", pageResult.getRecords(),total);
    }

    @Override
    public ResultVO<Courses> addCourse(Courses course) {
        try {
            // 检查课程编号在系统内是否唯一
            Courses existingCourse = this.getOne(new QueryWrapper<Courses>()
                    .eq("course_id", course.getCourseId()));
            if (existingCourse != null) {
                return ResultVO.fail("系统内已存在相同的课程编号，请重新输入");
            }
            // 检查课程名称在系统内是否唯一
            Courses existingCourse1 = this.getOne(new QueryWrapper<Courses>()
                    .eq("course_name", course.getCourseName()));
            if (existingCourse1 != null) {
                return ResultVO.fail("系统内已存在相同的课程名称，请重新输入");
            }

            boolean saveSuccess = this.save(course);
            if (!saveSuccess) {
                return ResultVO.fail("课程添加失败");
            }

            return ResultVO.success("课程添加成功", course);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVO.fail("添加课程时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Courses> updateCourse(Courses course) {
        try {
            // 1. 检查课程是否存在
            Courses existingCourse = this.getOne(new QueryWrapper<Courses>()
                    .eq("course_id", course.getCourseId()));
            if (existingCourse == null) {
                return ResultVO.fail("课程编号不存在");
            }

            // 2. 修改教学中的课程名称
            QueryWrapper<Teaches> teachesQuery = new QueryWrapper<>();
            teachesQuery.eq("course_id", course.getCourseId());
            List<Teaches> teachesList = teachesMapper.selectList(teachesQuery);
            if (!teachesList.isEmpty()) {
                return ResultVO.fail("该课程正在进行中，无法更新");
            }

            // 3. 更新课程信息（只更新非空字段）
            if (course.getCourseName() != null && !course.getCourseName().isEmpty()) existingCourse.setCourseName(course.getCourseName());
            if (course.getDepartment() != null && !course.getDepartment().isEmpty()) existingCourse.setDepartment(course.getDepartment());
            if (course.getCourseCredits() != null) existingCourse.setCourseCredits(course.getCourseCredits());
            if (course.getCourseDescription() != null && !course.getCourseDescription().isEmpty()) existingCourse.setCourseDescription(course.getCourseDescription());

            // 4. 执行更新操作
            boolean updateSuccess = this.updateById(existingCourse);
            if (!updateSuccess) {
                return ResultVO.fail("课程信息更新失败");
            }

            return ResultVO.success("课程信息更新成功", existingCourse);
        } catch (Exception e) {
            return ResultVO.fail("更新课程时发生异常：" + e.getMessage());
        }
    }
    @Override
    public ResultVO<Courses> deleteCourse(String courseId) {
        try {
            // 检查课程是否存在
            Courses existingCourse = this.getOne(new QueryWrapper<Courses>()
                    .eq("course_id", courseId));
            if (existingCourse == null) {
                return ResultVO.fail("课程编号不存在");
            }

            // 检查课程是否正在上
            List<Teaches> teachesList = teachesMapper.selectList(new QueryWrapper<Teaches>().eq("course_id", courseId));
            if (!teachesList.isEmpty()) {
                return ResultVO.fail("该课程正在进行中，无法删除");
            }
            System.out.println("删除courseid" + courseId);
            // 删除课程
            boolean deleteSuccess = this.removeById(courseId);
            if (!deleteSuccess) {
                return ResultVO.fail("课程删除失败");
            }
            return ResultVO.success("课程删除成功");
        } catch (Exception e) {
            return ResultVO.fail("删除课程时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Courses> getCourseDetail(String courseId) {
        try {
            // 检查课程是否存在
            QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
            if (queryWrapper.eq("course_id",courseId)==null){
                return ResultVO.fail("课程编号不存在");
            }
            Courses courseDetail = this.getOne(queryWrapper);
            // 返回课程详细信息
            return ResultVO.success("查询成功",courseDetail);
        } catch (Exception e) {
            // 处理异常
            return ResultVO.fail("获取课程详细信息时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<Courses>> getCourseListByDepartment(String department) {
        QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("department",department);
        List<Courses> coursesList=this.list(queryWrapper);
        if(coursesList==null){
            return ResultVO.fail("该学院下还未开设课程");
        }

        List<Courses> list = this.list(queryWrapper);
        int total= list.size();
        return ResultVO.success("查询成功",coursesList,total);
    }

    @Override
    public ResultVO<String> getCourseIdByName(String courseName) {
        QueryWrapper<Courses> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_name",courseName);
        Courses courses = this.getOne(queryWrapper);
        if(courses==null){
            return ResultVO.fail("没有该课程名称");
        }
        return ResultVO.success("查询成功",courses.getCourseId());
    }

}
